from django.views.generic import ListView, CreateView, DetailView, UpdateView, DeleteView, TemplateView
from app01.form import ArticleForm
from app01.models import Article
from django.contrib.auth.models import User


# Create your views here.
class ArticleListView(ListView):
    model = Article
    # queryset = Article.objects.filter(id__lt=2)
    template_name = 'index.html'
    context_object_name = 'article_list'
    # extra_context = {'title': 'List'}
    paginate_by = 10

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(object_list=object_list, **kwargs)
        context['title'] = "list"
        print(context)
        return context

    def get_queryset(self):
        return Article.objects.filter(id__gt=2)


class ArticleDetailView(DetailView):
    model = Article
    template_name = 'detail.html'
    context_object_name = 'article'
    extra_context = {'title': 'Detail'}


class ArticleCreateView(CreateView):
    model = Article
    form_class = ArticleForm
    # fields = ['name', 'content']
    template_name = 'create.html'
    extra_context = {'title': 'Create'}
    success_url = '/list'

    def form_valid(self, form):
        # form提交验证通过后的操作，会自动保存到数据库。
        user = self.request.user
        if isinstance(user, User):
            form.instance.user = self.request.user
        return super().form_valid(form)


class ArticleUpdateView(UpdateView):
    model = Article
    fields = ['name', 'content']
    template_name = 'update.html'
    extra_context = {'title': 'Update'}
    success_url = '/list'


class ArticleDeleteView(DeleteView):
    model = Article
    template_name = 'delete.html'
    success_url = '/list'


class ArticleTemplateView(TemplateView):
    model = Article
    extra_context = {'title': 'template'}
    template_name = 'template.html'
    context_object_name = 'article_list'
